package cn.passlink.www.Controller;
import cn.passlink.www.Enity.sysUser;
import cn.passlink.www.Server.CommentServer;
import cn.passlink.www.Utils.JsonUtils;
import cn.passlink.www.Utils.JwtUtils;
import cn.passlink.www.Utils.ReqDataCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/comment")
public class CommenController {
    @Resource
    private CommentServer commentServer;
    //上传评论，需要验证
    @PostMapping("/pull")
    public Map<String, Object> pull(@RequestBody Map<String, Object> requestData, HttpServletRequest request){
        String[] keys={"article_id","comment_id","content","isMain"};
        if(!ReqDataCheck.ReqDataCheckKeys(requestData,keys)) {
            log.error("请求数据错误");
            return JsonUtils.resultJson(403,"请求数据错误");
        }
        //获取accessToken
        String accessToken = request.getHeader("Authorization");
        //        未登录
        if (!StringUtils.hasText(accessToken)) {
            log.error("不存在token");
            return JsonUtils.resultJson(403,"权限不足");
        }
        if (accessToken.startsWith("Bearer ")) {
            log.error("不是Bearer类型");
            accessToken = accessToken.substring(7); // 去除前面的"Bearer "
        }

        //解析accessToken内的信息
        sysUser user = JwtUtils.getClaims(accessToken);
        if(user==null){
            log.error("token解析错误");
            return JsonUtils.resultJson(403,"请重新登陆再尝试！！！");
        }
        String article_id= (String) requestData.get("article_id");
        String comment_id= (String) requestData.get("comment_id");
        String content= (String) requestData.get("content");
        String isMain= (String) requestData.get("isMain");
        //只能是0、1
        if( !isMain.equals("1") && !isMain.equals("0")){
            log.error("isMain字段错误");
            return JsonUtils.resultJson(403,"评论失败！！！");
        }

        String user_id=user.getUser_id();
        if(     article_id.length()<8
                || content.isEmpty()
                || user_id.length()<8
                || content.length()>1000
                ){
            log.error("数据长度过长");
            return JsonUtils.resultJson(403,"数据非法！！！");
        }
        return commentServer.pullCom(user_id,article_id,comment_id,content,isMain);

    }

    //获取评论
    @GetMapping("/getList")
    public Map<String, Object> getList(@RequestParam("article_id") String article_id){
        if(article_id.length()<8) {
            log.error("请求数据错误");
            return JsonUtils.resultJson(403,"请求数据错误");
        }
        return commentServer.getList(article_id);
    }

}
